#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
 
char *base64_encode(const unsigned char *in, int32_t len)
{
    BIO     *bmem, *b64;
    BUF_MEM *b_ptr;
 
    b64 = BIO_new(BIO_f_base64());
    bmem = BIO_new(BIO_s_mem());
    b64 = BIO_push(b64, bmem);
    BIO_write(b64, in, len);
    BIO_flush(b64);
    BIO_get_mem_ptr(b64, &b_ptr);
 
    char *buff = (char *)calloc(1, b_ptr->length);
    if (buff == NULL) {
        printf("alloc memory fail\n");
        return NULL;
    }
 
    memcpy(buff, b_ptr->data, b_ptr->length - 1);
    buff[b_ptr->length - 1] = 0;
 
    BIO_free_all(b64);
 
    return buff;
}
 
char *base64_decode(unsigned char *in, int32_t len)
{
    BIO     *b64, *bmem;
 
    char *buffer = (char *)calloc(1, len);
    if (buffer == NULL) {
        printf("alloc memory fail\n");
        return NULL;
    }
 
    b64 = BIO_new(BIO_f_base64());
    bmem = BIO_new_mem_buf(in, len);
    bmem = BIO_push(b64, bmem);
 
    BIO_read(bmem, buffer, len);
 
    BIO_free_all(bmem);
 
    return buffer;
}
 
int main(int argc, char **argv)
{
    char *type = argv[1];
    char *str = NULL;
    char *out = NULL;
 
    if (type[0] == '-' && type[1] == 'e') {
        str = argv[2];
        out = base64_encode(str, strlen(str));
        printf("base64_encode(\"%s\"): %s\n", str, out);
    } else {
        str = (char *)calloc(1, strlen(argv[2]) + 1);
        if (str == NULL) {
            printf("calloc memory fail\n");
            return -1;
        }
        memcpy(str, argv[2], strlen(argv[2]));
        str[strlen(argv[2])] = '\n';
        str[strlen(argv[2])+1] = '\0';
        out = base64_decode(str, strlen(str));
        printf("base64_decode(\"%s\"): %s\n", argv[2], out);
        free(str);
    }
 
    free(out);
 
    return 0;
}
